package com.example.module_filemanage.MVVM.Module.QiNiu;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import com.example.module_base.Net.HttpClient;
import com.example.module_base.Net.ResponseHandler;
import com.example.module_filemanage.Interface.ICallBack;

import com.example.module_filemanage.Interface.IFileServer;
import com.example.module_filemanage.Interface.IUpLoadFile;
import com.example.module_filemanage.MVVM.Module.Entil.Item_FileInfo_module;
import com.example.module_filemanage.Public.Constant;
import com.example.module_filemanage.Public.Data;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCancellationSignal;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.util.StringUtils;
import com.qiniu.util.UrlSafeBase64;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.UUID;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

import static android.content.ContentValues.TAG;


/**
 * Created by ASUS on 2018/4/24.
 */

public class FileManager2 {
    private  ICallBack callBack;
    private FileManager2() {
    }

    public static FileManager2 getInstance() {
        return SingletonHolder.INSTANCE;
    }
    private static class SingletonHolder {
        private static final FileManager2 INSTANCE = new FileManager2();
    }
    public void delFile(final String bucket, final String key, final ICallBack iCallBack){
        this.callBack=iCallBack;
       // Log.e(TAG, "run: " );
        new Thread(new Runnable() {
            @Override
            public void run() {
                BucketManager bucketManager=ConfigManager.getInstance().getBucketManager();
                Bundle bundle=new Bundle();
                try {
                    bucketManager.delete(bucket, key);
                    bundle.putInt("code",200);
                } catch (QiniuException ex) {
                    //如果遇到异常，说明删除失败
                    System.err.println(ex.code());
                    System.err.println(ex.response.toString());
                    bundle.putInt("code",ex.code());
                    bundle.putString("message",ex.response.toString());

                }
              //  Log.e(TAG, "run: "+String.valueOf(bundle.getInt("code")) );
                android.os.Message message=myHandler.obtainMessage();
                message.setData(bundle);
                message.what=0;
                myHandler.sendMessage(message);

            }
        }).start();
//        Bundle bundle=new Bundle();
//        bundle.putInt("code",200);
//        bundle.putString("message","11");
//        android.os.Message message=myHandler.obtainMessage();
//        message.setData(bundle);
//        message.what=0;
//        myHandler.sendMessage(message);
    }
    public static void addSpaceName(final Context mContext, String newspacename){
        String newspace=UrlSafeBase64.encodeToString(newspacename);
        String ss="/mkbucketv2/"+newspace;
        HttpClient<IFileServer> _httpClient=new HttpClient(mContext,TokenManager.getInstance().getManageToken(ss+"\n"),IFileServer.class);
        Call<ResponseBody> _listCall=_httpClient.service(Constant.baseUrl3,true).addNewSpace(newspace);
        Log.e("onSuccess", "onSuccess: ");
        _httpClient.request(_listCall, new ResponseHandler<ResponseBody>() {
            @Override
            public void onSuccess(ResponseBody IO) {
                    Toast.makeText(mContext, "创建空间成功！退出刷新", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int code, String e) {
                Log.e("onfaile", "onfaile: " +e);
            }
        });
    }

    public  void rename(final String bucket, final String key, final String newkey, final ICallBack iCallBack){
        this.callBack=iCallBack;
        //构造一个带指定Zone对象的配置类
//...其他参数参考类注释
        new Thread(new Runnable() {
            @Override
            public void run() {
                String fromBucket = bucket;
                String fromKey = key;
                String toBucket = bucket;
                String toKey = newkey;
                BucketManager bucketManager=ConfigManager.getInstance().getBucketManager();
                Bundle bundle=new Bundle();
                try {
                    bucketManager.move(fromBucket, fromKey, toBucket, toKey);
                    bundle.putInt("code",200);
                } catch (QiniuException ex) {
                    //如果遇到异常，说明移动失败
                    System.err.println(ex.code());
                    System.err.println(ex.response.toString());
                    bundle.putInt("code",ex.code());
                    bundle.putString("message",ex.response.toString());

                }
                android.os.Message message=myHandler.obtainMessage();
                message.setData(bundle);
                message.what=0;
                myHandler.sendMessage(message);
            }
        }).start();

    }
    //文件上传
    private volatile boolean isCancelled = false;
    public void uploadFile(String filepath, String filename, String bucket, final IUpLoadFile upLoadFile){
        UploadManager uploadManager=ConfigManager.getInstance().getUploadBuckManager();

        File data = new File(filepath);
        String key = filename;

        String token = TokenManager.getInstance().getUpLoadManageToken(bucket,filename);
        uploadManager.put(data, key, token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        //res包含hash、key等信息，具体字段取决于上传策略的设置
                        if(info.isOK()) {
                            Log.i("qiniu", "Upload Success");
                            upLoadFile.complete();
                        } else {
                            Log.i("qiniu", "Upload Fail"+info.error);
                            upLoadFile.faile(info.error);
                            //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                        }

                        Log.i("qiniu", key + ",\r\n " + info + ",\r\n " + res);
                    }
                },   new UploadOptions(null, null, false,
                        new UpProgressHandler(){
                            public void progress(String key, double percent){
                                Log.i("qiniu", key + ": " + percent);
                                upLoadFile.progress(percent);
                            }
                        },  null));
    }
    //主线程
    Handler myHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch(msg.what) {
                case 0:
                    callBack.success(msg.getData());
                    break;
                default:
                    break;
            }
        }
    };
}
